package com.tencent50.easy;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 最大公共前缀
 * @date 2022/7/23 15:59
 */
public class Demo02 {
    public static void main(String[] args) {
        String[] strs={"flower","flow","flight"};
        System.out.println(longestCommonPrefix(strs));
    }
    public static String longestCommonPrefix(String[] strs) {
        String common="",com="";
        if(strs.length==0){
            return common;
        }
        if(strs.length==1){
            return strs[0];
        }
        String first=strs[0];
        for (int i = 0; i < first.length(); i++) {
            common=common+first.charAt(i);
            for (String str : strs) {
                while (!str.startsWith(common)){
                    return com;
                }
            }
            com=common;
        }
        return com;
    }
    //优解
    public static String longestCommonPrefix1(String[] strs) {
        if(strs.length==0)return "";
        //公共前缀比所有字符串都短，随便选一个先
        String s=strs[0];
        for (String string : strs) {
            while(!string.startsWith(s)){
                if(s.length()==0)return "";
                //公共前缀不匹配就让它变短！
                s=s.substring(0,s.length()-1);
            }
        }
        return s;
    }
}
